/// <reference types="node" />

import { Client, I } from 'libtcp';
import config = require('./config');
import fs = require('fs');
import path = require('path');
import tool = require('./tool');

export type Fileinfo = config.Fileinfo;
export type BeforeReceiveFunction = tool.BeforeReceiveFunction;
export type ReceivingFunction = tool.ReceivingFunction;
export type ReceivedFunction = tool.ReceivedFunction;

export class FSClient {
	private g_index = 0;

	constructor(private client: Client) {
	}

	public sendFile(filename: string, message: any) {
		return tool.sendFile(filename, message, this.client);
	}

	public async requestFile(message: any, receiving?: ReceivingFunction) {
		let index: number = await this.client.emitSync(config.FILE_REQUEST_MESSAGE, message);
		const CONTENT_MESSAGE = config.FILE_REQUEST_MESSAGE + index + '!!';
		const CONTENT_END_MESSAGE = config.FILE_REQUEST_MESSAGE + index + '!!end';

		let fileinfo: Fileinfo = null;
		let contents: Buffer[] = [];
		let received_size = 0;
		this.client.on(CONTENT_MESSAGE, (arg: any) => {
			if (fileinfo == null) {
				fileinfo = arg;
			} else {
				received_size += arg.length;
				contents.push(arg);
			}
			if (fileinfo && receiving) {
				receiving(fileinfo, null, received_size);
			}
		});
		this.client.emit(CONTENT_MESSAGE);
		await this.client.waitForEvent(CONTENT_END_MESSAGE);
		this.client.removeAllListeners(CONTENT_MESSAGE);
		return {
			fileinfo: fileinfo,
			content: Buffer.concat(contents)
		};
	}
}